package com.company.ThreadLearn;

public class ThreadClass extends Thread {
    String name;
    final static int LOOP = 100;
    public static int count = 0;
    volatile boolean running = true;
    public static final Object LOCK = new Object();
    public ThreadClass(String name) throws InterruptedException {
        this.name = name;
        Thread t1 = new AddThread();
        Thread t2 = new DecThread();
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }

    public void run() {
        first();
        while (running){
            System.out.println("Hello");
            try {
                Thread.sleep(100);
            }catch (InterruptedException e){
                System.out.println("Thread end");
                break;
            }
        }
    }

    public void first() {
//        System.out.println("main start ...");
//        Thread t = new Thread() {
//            public void run() {
//                System.out.println("thread run ...");
//                System.out.println("thread end ...");
//            }
//        };
//        t.start();
//        System.out.println("main end ...");
        for (int i =0;i<3;i++){
            System.out.println("Hello,run1 "+name+i+".");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class DecThread extends Thread{
    @Override
    public void run() {
        for(int i =0;i< ThreadClass.LOOP;i++){
            synchronized(ThreadClass.LOCK){
                ThreadClass.count -=1;
            }
        }
    }
}
class AddThread extends Thread{
    @Override
    public void run() {
        for(int i =0;i< ThreadClass.LOOP;i++){
            synchronized(ThreadClass.LOCK){
                ThreadClass.count +=1;
            }
        }
    }
}
